<?php
namespace app\common\helper\payment;
use app\common\logic\DataSettingLogic;
use EasyWeChat\Factory;
use app\common\model\OrderModel;
class  PaymentPlatformHelper{
    private $app;
    public function __construct() {
        $DataSettingLogic = new DataSettingLogic();
        $config = $DataSettingLogic->getData('payment');
        $certFile = $this->getCertDir().md5($config['api_cert']).'_cert.perm';
        $keyFile  = $this->getCertDir().md5($config['api_key']).'_key.perm';
        if(!file_exists($certFile)){
             file_put_contents($certFile, $config['api_cert']);
        }
        if(!file_exists($keyFile)){
             file_put_contents($keyFile, $config['api_key']);
        }
        $paymentConfig = [
            'app_id'         => $config['app_id'],
            'mch_id'         => $config['mach_id'],
            'key'            => $config['api_auth'],
            'cert_path'      => $certFile,
            'key_path'       => $keyFile,
            'notify_url'     => '',
        ];
        $this->app = Factory::payment($paymentConfig);
    }
    
    //获取支付的二维码地址
    public function getPayment($orderId){
         if(null === $order = OrderModel::find($orderId)){
             return false;
         }
         $unifyOrder = [
            'body' => $order['type'] == 1 ? '小程序续费' : '短信购买',
            'out_trade_no' => 'platform_'.date('Ymd').'_'. $order['order_id'],
            'total_fee' => (int)($order['price'] * 100),//调试设置为1
            'notify_url' => $this->getBackUrl(), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'NATIVE', // 请对应换成你的支付方式对应的值类型
         ];
         $return = $this->app->order->unify($unifyOrder);
         if($return['return_code'] == 'SUCCESS' && $return['result_code'] == 'SUCCESS' ){
             return  $return['code_url'];
         }
        return false;
    }
    
    //平台支付的回调处理
    public function respond(){
         $response = $this->app->handlePaidNotify(function($message, $fail){
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                if ($message['result_code'] === 'SUCCESS') { //支付成功
                   $datas = explode('_',$message['out_trade_no']);
                   $orderId = $datas[2] ?? 0;
                   if(empty($orderId)){
                       return $fail('订单不存在');
                   }
                   $order = OrderModel::find($orderId);
                    if(null === $order){
                        return $fail('订单不存在');
                    }
                   if($order->is_paid == 0){ //更新影响了记录数
                       $order->is_paid = 1;
                       $order->payinfo = json_encode($message);
                       $order->save();
                       $className="\\app\\".$order->app_name."\\logic\\PlatformPaymentRespondLogic";
                       $className::respond($orderId); //进行发货处理
                   }
                } 
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true; // 返回处理完成
        });

        $response->send();
    }
    
    public function getCertDir(){
        $dir = root_path().'/cert/platform/';
        if(!is_dir($dir)){
            mkdir($dir,0755,true);
        }
        return $dir;
    }
    
    public function getBackUrl(){
        return env('domain.base_url', 'https://域名/').'platform/respond';
    }
}